import uvicorn
from apscheduler.schedulers.background import BackgroundScheduler
from fastapi import FastAPI, Request
from fastapi.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware

from config.env import StartConfig
from config.get_db import init_create_table
from config.get_redis import RedisUtil
from config.get_scheduler import SchedulerUtil
from core.controller.cms_alert_message_controller import alertMessageController
from core.controller.cms_alert_rule_controller import alertRuleController
from core.controller.cms_car_minitor_controller import carMinitorController
from core.controller.cms_car_track_controller import carTrackController
from core.controller.cms_gaode_fence_controller import gaodeFenceController
from core.controller.cms_gaode_service_controller import gaodeServiceController
from core.controller.cms_gaode_terminal_controller import gaodeTerminalController
from core.controller.cms_gaode_trace_controller import gaodeTraceController
from core.controller.cms_terminal_point_controller import terminalPointController
from core.controller.monitor_controller import monitorController
from utils.common_util import worship
from utils.log_util import logger
from utils.response_util import *

app = FastAPI(
    title='Dash-FastAPI',
    description='Dash-FastAPI接口文档',
    version='1.0.0',
    docs_url="/gis/docs",
    redoc_url="/gis/redoc",
    openapi_url="/gis/openapi.json"
)

# 后台api允许跨域
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.on_event("startup")
async def startup_event():
    logger.info("Dash-FastAPI开始启动")
    worship()
    await init_create_table()
    await SchedulerUtil.init_system_scheduler()
    # app.state.redis = await RedisUtil.create_redis_pool()
    logger.info("Dash-FastAPI启动成功")


@app.on_event("shutdown")
async def shutdown_event():
    await RedisUtil.close_redis_pool(app)


# 自定义token检验异常
@app.exception_handler(AuthException)
async def auth_exception_handler(request: Request, exc: AuthException):
    return response_401(data=exc.data, message=exc.message)


# 自定义权限检验异常
@app.exception_handler(PermissionException)
async def permission_exception_handler(request: Request, exc: PermissionException):
    return response_403(data=exc.data, message=exc.message)


@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        content=jsonable_encoder({"message": exc.detail, "code": exc.status_code}),
        status_code=exc.status_code
    )


app.include_router(gaodeServiceController, prefix="/gis", tags=['高德服务'])
app.include_router(gaodeFenceController, prefix="/gis", tags=['高德围栏'])
app.include_router(gaodeTerminalController, prefix="/gis", tags=['高德终端'])
app.include_router(gaodeTraceController, prefix="/gis", tags=['高德轨迹'])
app.include_router(carTrackController, prefix="/gis", tags=['轨迹节点'])
app.include_router(terminalPointController, prefix="/gis", tags=['设备轨迹'])
app.include_router(carMinitorController, prefix="/gis", tags=['车辆监控'])
app.include_router(alertRuleController, prefix="/gis", tags=['告警规则'])
app.include_router(alertMessageController, prefix="/gis", tags=['告警信息'])
app.include_router(monitorController, prefix="/gis", tags=['告警信息'])

if __name__ == '__main__':
    uvicorn.run(app='app:app', host=StartConfig.HOST, port=StartConfig.PORT, reload=True)